<template>
  <div class="marketing-plan-panel">
    <!-- 用户购买意向分析 -->
    <div class="intent-analysis-section">
      <h3>用户购买意向分析</h3>
      <div class="intent-info">
        <div class="intent-level">
          <span class="label">购买意向等级:</span>
          <el-tag :type="getIntentTagType(prediction.intentLevel)" size="large">
            {{ getIntentLevelText(prediction.intentLevel) }}
          </el-tag>
        </div>
        <div class="intent-probability">
          <span class="label">购买概率:</span>
          <div class="probability-display">
            <el-progress 
              :percentage="Math.round(prediction.purchaseProbability * 100)" 
              :stroke-width="12"
              :color="getIntentColor(prediction.intentLevel)"
            />
            <span class="probability-text">{{ Math.round(prediction.purchaseProbability * 100) }}%</span>
          </div>
        </div>
        <div class="predicted-amount">
          <span class="label">预测购买金额:</span>
          <span class="amount-text">¥{{ prediction.predictedAmount.toLocaleString() }}</span>
        </div>
      </div>
    </div>

    <!-- 营销计划配置 -->
    <div class="plan-configuration-section">
      <h3>营销计划配置</h3>
      <el-form :model="planForm" label-width="120px">
        <el-form-item label="计划名称">
          <el-input 
            v-model="planForm.name" 
            placeholder="请输入营销计划名称"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="营销策略">
          <el-select v-model="planForm.strategy" placeholder="请选择营销策略" style="width: 100%">
            <el-option 
              v-for="strategy in marketingStrategies" 
              :key="strategy.value"
              :label="strategy.label" 
              :value="strategy.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="优惠类型">
          <el-radio-group v-model="planForm.discountType">
            <el-radio label="percentage">百分比折扣</el-radio>
            <el-radio label="fixed">固定金额</el-radio>
            <el-radio label="coupon">优惠券</el-radio>
            <el-radio label="gift">赠品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="优惠力度" v-if="planForm.discountType !== 'gift'">
          <div class="discount-config">
            <el-slider
              v-model="planForm.discountValue"
              :min="getDiscountMin()"
              :max="getDiscountMax()"
              :step="getDiscountStep()"
              show-stops
              show-input
              :format-tooltip="formatDiscountTooltip"
              style="margin-right: 20px;"
            />
            <span class="discount-preview">
              {{ getDiscountPreview() }}
            </span>
          </div>
        </el-form-item>

        <el-form-item label="推广渠道">
          <el-checkbox-group v-model="planForm.channels">
            <el-checkbox label="email">邮件营销</el-checkbox>
            <el-checkbox label="sms">短信推送</el-checkbox>
            <el-checkbox label="push">APP推送</el-checkbox>
            <el-checkbox label="banner">站内横幅</el-checkbox>
            <el-checkbox label="social">社交媒体</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="执行时间">
          <el-date-picker
            v-model="planForm.executeTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="目标产品">
          <el-select 
            v-model="planForm.targetProducts" 
            multiple 
            placeholder="选择推荐产品"
            style="width: 100%"
          >
            <el-option 
              v-for="product in availableProducts" 
              :key="product.id"
              :label="product.name" 
              :value="product.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="计划描述">
          <el-input
            v-model="planForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入营销计划描述"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 推荐营销模板 -->
    <div class="marketing-templates-section">
      <h3>推荐营销模板</h3>
      <div class="templates-grid">
        <div 
          v-for="template in recommendedTemplates" 
          :key="template.id"
          class="template-card"
          :class="{ active: selectedTemplate === template.id }"
          @click="selectTemplate(template)"
        >
          <div class="template-header">
            <h4>{{ template.name }}</h4>
            <el-tag :type="template.effectiveness" size="small">
              {{ getEffectivenessText(template.effectiveness) }}
            </el-tag>
          </div>
          <div class="template-content">
            <p>{{ template.description }}</p>
            <div class="template-metrics">
              <div class="metric">
                <span class="metric-label">转化率:</span>
                <span class="metric-value">{{ template.conversionRate }}%</span>
              </div>
              <div class="metric">
                <span class="metric-label">ROI:</span>
                <span class="metric-value">{{ template.roi }}x</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预期效果预测 -->
    <div class="effect-prediction-section">
      <h3>预期效果预测</h3>
      <div class="prediction-metrics">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="prediction-card">
              <div class="prediction-icon">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="prediction-content">
                <h4>{{ predictedEffect.conversionRate }}%</h4>
                <p>预期转化率</p>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="prediction-card">
              <div class="prediction-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="prediction-content">
                <h4>¥{{ predictedEffect.expectedRevenue.toLocaleString() }}</h4>
                <p>预期收入</p>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="prediction-card">
              <div class="prediction-icon">
                <el-icon><Star /></el-icon>
              </div>
              <div class="prediction-content">
                <h4>{{ predictedEffect.roi }}x</h4>
                <p>投资回报率</p>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="prediction-card">
              <div class="prediction-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="prediction-content">
                <h4>{{ predictedEffect.reachUsers }}</h4>
                <p>触达用户数</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="handleCancel">取消</el-button>
      <el-button @click="previewPlan">预览计划</el-button>
      <el-button type="primary" @click="createPlan" :loading="creating">
        创建营销计划
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { TrendCharts, Money, Star, User } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  prediction: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['plan-created', 'cancel'])

// 响应式数据
const creating = ref(false)
const selectedTemplate = ref(null)

// 营销计划表单
const planForm = reactive({
  name: `${props.prediction.userName}的个性化营销计划`,
  strategy: '',
  discountType: 'percentage',
  discountValue: 15,
  channels: ['email', 'push'],
  executeTime: [
    new Date(),
    new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
  ],
  targetProducts: [],
  description: ''
})

// 营销策略选项
const marketingStrategies = [
  { label: '个性化推荐', value: 'personalized' },
  { label: '限时促销', value: 'flash_sale' },
  { label: '新品推广', value: 'new_product' },
  { label: '复购激励', value: 'repurchase' },
  { label: '会员专享', value: 'vip_exclusive' }
]

// 可选产品
const availableProducts = [
  { id: 'P001', name: 'iPhone 15 Pro' },
  { id: 'P002', name: '无线耳机' },
  { id: 'P003', name: '智能手表' },
  { id: 'P004', name: '平板电脑' },
  { id: 'P005', name: '笔记本电脑' }
]

// 推荐营销模板
const recommendedTemplates = computed(() => {
  const baseTemplates = [
    {
      id: 1,
      name: '高意向用户转化',
      description: '针对高购买意向用户的精准营销策略',
      effectiveness: 'success',
      conversionRate: 28,
      roi: 4.2,
      config: {
        strategy: 'personalized',
        discountType: 'percentage',
        discountValue: 20,
        channels: ['email', 'push', 'banner']
      }
    },
    {
      id: 2,
      name: '限时抢购促销',
      description: '创造紧迫感，促进快速决策购买',
      effectiveness: 'primary',
      conversionRate: 22,
      roi: 3.8,
      config: {
        strategy: 'flash_sale',
        discountType: 'percentage',
        discountValue: 25,
        channels: ['sms', 'push', 'social']
      }
    },
    {
      id: 3,
      name: '个性化产品推荐',
      description: '基于用户偏好的个性化产品推荐',
      effectiveness: 'warning',
      conversionRate: 18,
      roi: 3.2,
      config: {
        strategy: 'personalized',
        discountType: 'coupon',
        discountValue: 50,
        channels: ['email', 'banner']
      }
    }
  ]

  // 根据购买意向调整推荐
  if (props.prediction.intentLevel === 'High') {
    return baseTemplates.sort((a, b) => b.conversionRate - a.conversionRate)
  }
  return baseTemplates
})

// 预期效果
const predictedEffect = computed(() => {
  const baseConversion = 15
  const intentBonus = props.prediction.intentLevel === 'High' ? 10 : 
                     props.prediction.intentLevel === 'Medium' ? 5 : 0
  const discountBonus = planForm.discountValue * 0.3
  const channelBonus = planForm.channels.length * 2
  
  const conversionRate = Math.min(35, baseConversion + intentBonus + discountBonus + channelBonus)
  const expectedRevenue = Math.round(props.prediction.predictedAmount * conversionRate / 100)
  const cost = Math.round(expectedRevenue * planForm.discountValue / 100)
  const roi = cost > 0 ? (expectedRevenue / cost).toFixed(1) : 0
  const reachUsers = Math.round(1000 + planForm.channels.length * 200)

  return {
    conversionRate: Math.round(conversionRate),
    expectedRevenue,
    roi,
    reachUsers
  }
})

// 方法
const getIntentTagType = (intentLevel) => {
  const typeMap = {
    'High': 'success',
    'Medium': 'warning',
    'Low': 'danger'
  }
  return typeMap[intentLevel] || 'info'
}

const getIntentLevelText = (intentLevel) => {
  const textMap = {
    'High': '高意向',
    'Medium': '中意向',
    'Low': '低意向'
  }
  return textMap[intentLevel] || '未知'
}

const getIntentColor = (intentLevel) => {
  const colorMap = {
    'High': '#67C23A',
    'Medium': '#E6A23C',
    'Low': '#F56C6C'
  }
  return colorMap[intentLevel] || '#909399'
}

const getDiscountMin = () => {
  return planForm.discountType === 'fixed' ? 10 : 5
}

const getDiscountMax = () => {
  return planForm.discountType === 'fixed' ? 500 : 50
}

const getDiscountStep = () => {
  return planForm.discountType === 'fixed' ? 10 : 5
}

const formatDiscountTooltip = (value) => {
  if (planForm.discountType === 'percentage') {
    return `${value}% 折扣`
  } else if (planForm.discountType === 'fixed') {
    return `¥${value} 减免`
  } else if (planForm.discountType === 'coupon') {
    return `¥${value} 优惠券`
  }
  return `${value}`
}

const getDiscountPreview = () => {
  const amount = props.prediction.predictedAmount
  if (planForm.discountType === 'percentage') {
    const discount = Math.round(amount * planForm.discountValue / 100)
    return `节省 ¥${discount.toLocaleString()}`
  } else if (planForm.discountType === 'fixed') {
    return `节省 ¥${planForm.discountValue}`
  } else if (planForm.discountType === 'coupon') {
    return `¥${planForm.discountValue} 优惠券`
  }
  return ''
}

const getEffectivenessText = (effectiveness) => {
  const textMap = {
    'success': '高效',
    'primary': '推荐',
    'warning': '一般'
  }
  return textMap[effectiveness] || '未知'
}

const selectTemplate = (template) => {
  selectedTemplate.value = template.id
  Object.assign(planForm, template.config)
}

const previewPlan = () => {
  ElMessage.info('营销计划预览功能开发中...')
}

const createPlan = async () => {
  if (!planForm.name.trim()) {
    ElMessage.warning('请输入计划名称')
    return
  }

  if (!planForm.strategy) {
    ElMessage.warning('请选择营销策略')
    return
  }

  if (planForm.channels.length === 0) {
    ElMessage.warning('请选择至少一个推广渠道')
    return
  }

  creating.value = true
  
  try {
    // 模拟创建营销计划
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    const plan = {
      userId: props.prediction.userId,
      userName: props.prediction.userName,
      ...planForm,
      predictedEffect: predictedEffect.value,
      createdAt: new Date().toISOString()
    }
    
    emit('plan-created', plan)
    ElMessage.success('营销计划创建成功')
  } catch (error) {
    ElMessage.error('营销计划创建失败')
  } finally {
    creating.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 监听器
watch(() => planForm.discountType, (newType) => {
  // 根据优惠类型调整默认值
  if (newType === 'percentage') {
    planForm.discountValue = 15
  } else if (newType === 'fixed') {
    planForm.discountValue = 50
  } else if (newType === 'coupon') {
    planForm.discountValue = 100
  }
})
</script>

<style scoped>
.marketing-plan-panel {
  padding: 20px 0;
}

.intent-analysis-section,
.plan-configuration-section,
.marketing-templates-section,
.effect-prediction-section {
  margin-bottom: 32px;
}

.intent-analysis-section h3,
.plan-configuration-section h3,
.marketing-templates-section h3,
.effect-prediction-section h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 8px;
}

/* 意向分析 */
.intent-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.intent-level,
.intent-probability,
.predicted-amount {
  display: flex;
  align-items: center;
  gap: 12px;
}

.intent-level .label,
.intent-probability .label,
.predicted-amount .label {
  font-size: 14px;
  color: #666;
  min-width: 120px;
}

.probability-display {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.probability-display .el-progress {
  flex: 1;
  max-width: 200px;
}

.probability-text,
.amount-text {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 优惠配置 */
.discount-config {
  display: flex;
  align-items: center;
  width: 100%;
}

.discount-preview {
  font-size: 14px;
  font-weight: 600;
  color: #67C23A;
  min-width: 120px;
}

/* 营销模板 */
.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.template-card {
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.template-card:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.template-card.active {
  border-color: #409EFF;
  background: #f0f9ff;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.template-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.template-content p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.template-metrics {
  display: flex;
  gap: 16px;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #999;
}

.metric-value {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

/* 预期效果 */
.prediction-metrics {
  margin-top: 16px;
}

.prediction-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
}

.prediction-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.prediction-content h4 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 700;
  color: #333;
}

.prediction-content p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

@media (max-width: 768px) {
  .templates-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
  
  .intent-level,
  .intent-probability,
  .predicted-amount {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .probability-display {
    width: 100%;
  }
  
  .discount-config {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
